package com.example.mvplogin.login;

import android.content.Context;
import android.util.Log;

import com.example.mvplogin.utils.DialogUtils;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public abstract class ResponseObserver<T> implements Observer<LoginResponseWrapper<T>> {
    Context mContext;
    boolean isShow;

    public ResponseObserver(Context context, boolean isShow) {
        mContext = context;
        this.isShow = isShow;
    }

    abstract public  void success(T t);

    abstract public void fail(String errorCode);

    @Override
    public void onSubscribe(Disposable d) {//订阅成功,即观察者和被观察者建立了连接的回调
        if (isShow) {
            DialogUtils.dialogUtils.show(mContext);
        }
    }

    //上游流下的数据
    @Override
    public void onNext(LoginResponseWrapper<T> tLoginResponseWrapper) {
        Log.d("ResponseObserver","错误码为==="+tLoginResponseWrapper.errorCode);
        if (tLoginResponseWrapper.data == null) {
            //失败
            fail(tLoginResponseWrapper.errorMsg);
        } else {
            //成功
            success(tLoginResponseWrapper.data);
        }
    }

    //上游流下的失败
    @Override
    public void onError(Throwable e) {
        if (isShow) {
            DialogUtils.dialogUtils.cancel();
        }

        fail(e.getMessage());
    }


    //停止
    @Override
    public void onComplete() {
        if (isShow) {
            DialogUtils.dialogUtils.cancel();
        }
    }

}
